<template>
  <div>
    <div class="projection_box">
      <TabPoint :pointList="pointList"></TabPoint>

      <div class="content" id="pointBox">
        <!-- 查询 -->
        <Search :form="searchForm" v-model="searchForm"></Search>
        <!-- 注解 -->
        <Notes :items="treeItems" ref="notesRef"></Notes>
        <!-- 流处理 -->
        <div id="handlePoin">
          <div class="form_title itemScrollWrapper">输入</div>
          <FlowHnadle
            :sourceCellNames="sourceCellNames"
            ref="leftflowHnadleRef"
            title="left"
            @inputExtensions="inputExtensions"
            @changeOutputSource="changeOutputSource"
          ></FlowHnadle>
          <div class="source_box">
            <div class="my_required title">加入类型</div>
            <el-select
              v-model="joinType"
              placeholder="请选择"
              style="width: 100%"
              size="small"
            >
              <el-option
                v-for="item in joinTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <FlowHnadle
            @changeOutputSource="changeOutputSource"
            @inputExtensions="inputExtensions"
            :sourceCellNames="sourceCellNames"
            ref="rightflowHnadleRef"
            title="right"
          ></FlowHnadle>
          <div class="source_box">
            <div class="my_required title">条件</div>
            <PopoverInput
              @changeRadio="changeRadio"
              objKey="funArrAll"
              v-model="onVal"
              keys="conductValue"
            ></PopoverInput>
          </div>
        </div>

        <!-- 投影 -->
        <Projection
          :objKey="'funArr'"
          objKeyFilter="funArrFilter"
          :attributeList="attributeList"
          :extensionsLR="extensionsLR"
          v-model="grouping"
        ></Projection>
        <!-- 输出 -->
        <Output
          @handDelOrderBy="handDelOrderBy"
          @handAddOrderBy="handAddOrderBy"
          :attributeList="attributeList"
          v-model="output"
          attrKey="sourceCell"
        ></Output>
      </div>
    </div>
    <!-- 确认取消公共组件 -->
    <top-operation-button @submit="submit" @handClose="handClose" />
  </div>
</template>

<script>
import TopOperationButton from "../CommonComponents/TopOperationButton";
import TabPoint from "@/components/TabPoint";
import Search from "./component/Search.vue";
import FlowHnadle from "./component/FlowHandle.vue";
import Notes from "./component/Notes.vue";
import Projection from "@/components/Projection";
import Output from "@/components/Output";
import { getMetadata } from "@/api/project";
import { validate } from "./js/validate";
import { setLrTarArr } from "./js/index";
import PopoverInput from "@/components/PopoverInput";
import {
  setFunctiondata,
  setStreamHandlerList,
  settargetCellAttr,
  setSourceCellAttr,
  setUserAttr,
} from "../projectionPage/js/index";
import { mapGetters } from "vuex";
import { generateId, reverseJson, empty } from "@/utils/index";
import _ from "lodash";
export default {
  components: {
    TopOperationButton,
    Output,
    TabPoint,
    Search,
    FlowHnadle,
    Notes,
    Projection,
    PopoverInput,
  },
  computed: {
    ...mapGetters(["extensions"]),
    // 后一个节点的属性
    relateData() {
      // relateData.targetCell.name
      return this.$store.state.projection.relateData;
    },
    extensionsLR() {
      let attrArr =
        this.$store.state.projection.extensions.funArrAll.find(
          (item) => item.name == "属性"
        )?.list || [];
      attrArr = attrArr.filter((item) => {
        return item.isOption;
      });
      return attrArr;
      // if (JSON.stringify(this.$store.state.projection.extensions) !== "{}") {
      //   let attrArr =
      //     this.$store.state.projection.extensions.funArrAll.find(
      //       (item) => item.name == "属性"
      //     )?.list || [];

      //   attrArr = attrArr.filter((item) => {
      //     return item.id == "left-attr" || item.id == "right-attr";
      //   });
      //   return attrArr;
      // } else {
      //   return [];
      // }
    },
  },
  data() {
    return {
      onVal: "",
      joinType: "",
      joinTypeList: [
        {
          name: "join",
          id: "JOIN",
        },
        {
          name: "left_outer_join",
          id: "LEFT_OUTER_JOIN",
        },
        {
          name: "right_outer_join",
          id: "RIGHT_OUTRT_JOIN",
        },
        {
          name: "full_outer_join",
          id: "FULL_OUTER_JOIN",
        },
      ],
      // 查询
      searchForm: {
        queryName: "",
      },
      // 输出
      output: {
        orderCh: false,
        orderBy: [], //按属性排序
        checkedLimit: false, //限制
        limit: "",
        checkedOffset: false, //位移
        offset: "",
        checkedOutputRateLimit: false, //输出速率
        outputRateLimit: "",
        // 操作下边的数据
        queryOutput: {
          type: "INSERT",
          target: "", //插入
          output: {
            eventType: "CURRENT_EVENTS", //事件类型
            // set选中传-选中整个都不传
            checkedSet: false,
            set: [],
          },
          // on: "",
        },
      },
      // 投影
      grouping: {
        groupBy: [], //按属性分组
        having: "", //过滤
        attrChecked: false,
        checkedFilter: false,
        select: {
          type: "ALL", //ALL USER_DEFINED 所有属性,用户自定义属性
          value: [], //用户自定义属性
        },
      },
      treeItems: [],
      form: { name: "" },
      rules: {},
      firstAttr: {},
      pointList: [
        {
          name: "查询",
          id: "searchPoin",
          val: "searchPoin",
        },
        {
          name: "注释",
          id: "notesPoin",
          val: "notesPoin",
        },
        {
          name: "输入",
          id: "handlePoin",
          val: "handlePoin",
        },

        {
          name: "投影",
          id: "prijectionPoin",
          val: "prijectionPoin",
        },
        {
          name: "输出",
          id: "output",
          val: "output",
        },
      ],
      attributeList: [],
      streamHandlerList: [],
      targetCellAttr: [],
      sourceCellNames: [],
      sourceCellAttributeList: [],
    };
  },
  props: {
    nodeDataRight: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    nodeDataRight: {
      handler: async function (newData, oldData) {
        let tempdata = _.cloneDeep(newData);
        console.log(tempdata, "tempdata");
        const { objectState } = tempdata;
        const {
          limit,
          offset,
          outputRateLimit,
          queryOutput,
          orderBy,
          groupBy,
          having,
          select,
          queryName,
          queryInput,
          annotationListObjects,
          relateData,
        } = tempdata;
        let { sourceCell, targetCell } = relateData;
        this.sourceCellNames = sourceCell;

        if (relateData) {
          this.$store.commit("projection/setExtensions", {
            relateData: relateData,
            isName: targetCell.name,
          });
          this.$store.commit("projection/setRelateData", relateData);
        }
        console.time("start");
        if (this.sourceCellNames && this.sourceCellNames.length !== 0) {
          this.$nextTick(() => {
            this.$refs["leftflowHnadleRef"].outputSource =
              this.sourceCellNames[0].name;
            this.$refs["rightflowHnadleRef"].outputSource =
              this.sourceCellNames[1].name;
          });
        }
        console.log(tempdata, "节点信息");
        // 传递节点数据-合并metadata的数据

        this.searchForm.queryName = tempdata.queryName || "";
        const name = targetCell.name;
        // 后一个节点属性整理
        targetCell.attributeList = settargetCellAttr(
          targetCell.attributeList,
          name
        );

        this.targetCellAttr = targetCell.attributeList;
        // 设置来源节点名称
        if (targetCell) {
          this.attributeList = targetCell.attributeList;
          this.setAttrArr(this.attributeList);
        }

        this.$nextTick(async () => {
          // left right
          this.setqueryInput(queryInput, sourceCell);
        });
        // 注解
        if (annotationListObjects && annotationListObjects.length !== 0) {
          this.setAnnotation(annotationListObjects);
        }
        console.timeEnd("start");
        this.searchForm.queryName = queryName;
        // 输出数据回显
        if (limit) {
          this.output.checkedLimit = true;
        } else {
          this.output.checkedLimit = false;
        }
        if (offset) {
          this.output.checkedOffset = true;
        } else {
          this.output.checkedOffset = false;
        }
        if (orderBy && orderBy.length != 0) {
          this.output.orderCh = true;
          this.output.orderBy = orderBy;
        } else {
          // 如果orderBy没值,给一个默认值,选中的时候方便展示
          this.output.orderCh = false;
          this.output.orderBy = [
            {
              id: generateId(),
              attrValue: "",
              sortValue: "",
              attributeList: this.attributeList,
            },
          ];
        }
        if (outputRateLimit) {
          this.output.checkedOutputRateLimit = true;
        } else {
          this.output.checkedOutputRateLimit = false;
        }
        this.output = {
          ...this.output,
          limit,
          offset,
          outputRateLimit,
        };
        // set有值
        this.output.queryOutput.target = targetCell.name;
        if (queryOutput && queryOutput.output.eventType) {
          this.output.queryOutput.output.eventType =
            queryOutput.output.eventType;
        }
        if (
          queryOutput &&
          queryOutput.output.set &&
          queryOutput.output.set.length !== 0
        ) {
          this.output.queryOutput.output.checkedSet = true;
        } else {
          this.output.queryOutput.output.checkedSet = false;
        }

        // 判断过滤是否有值-有值打开
        if (having && having != "") {
          this.grouping.checkedFilter = true;
          this.grouping.having = having;
        } else {
          this.grouping.checkedFilter = false;
        }
        // 判断是否是用户自定义
        if (select && select.value && select.value.length !== 0) {
          this.grouping.select.type = select.type;
          // this.grouping.attrChecked = true;
          // 后一个节点的属性名是唯一的 此处要进行合并和后一个节点关联 this.targetCellAttr
          this.grouping.select.value = setUserAttr(
            select.value,
            this.targetCellAttr
          );
        } else {
          // this.grouping.attrChecked = false;
          this.grouping.select.value = setUserAttr([], this.targetCellAttr);
        }
        if (groupBy && groupBy.length != 0) {
          this.grouping.attrChecked = true;
          this.grouping.groupBy = groupBy;
        } else {
          this.grouping.attrChecked = false;
          this.grouping.groupBy = [];
        }

        // if (objectState != "new") {
        // }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    changeOutputSource(title, val, vflowAs, vflowAsVal, isUnidirectional) {
      this.$nextTick(() => {
        let { flowAs: rflowAs } = this.$refs["rightflowHnadleRef"];
        let { flowAs: lflowAs } = this.$refs["leftflowHnadleRef"];
        if (title === "left") {
          // 判断对方是否选中
          if (rflowAs) {
            // 参数互换
            this.$refs["leftflowHnadleRef"].flowAsVal =
              this.$refs["rightflowHnadleRef"].flowAsVal;
            this.$refs["leftflowHnadleRef"].flowAs = true;
            this.$refs["rightflowHnadleRef"].flowAsVal = vflowAsVal;
          } else {
            this.$refs["leftflowHnadleRef"].flowAsVal = "";
            this.$refs["leftflowHnadleRef"].flowAs = false;
          }
          this.$refs["rightflowHnadleRef"].outputSource = val;
          this.$refs["leftflowHnadleRef"].isUnidirectional =
            this.$refs["rightflowHnadleRef"].isUnidirectional;
          this.$refs["rightflowHnadleRef"].isUnidirectional = isUnidirectional;
        } else {
          // 判断对方是否选中
          if (lflowAs) {
            // 参数互换
            this.$refs["rightflowHnadleRef"].flowAsVal =
              this.$refs["leftflowHnadleRef"].flowAsVal;
            this.$refs["rightflowHnadleRef"].flowAs = true;
            this.$refs["leftflowHnadleRef"].flowAsVal = vflowAsVal;
          } else {
            this.$refs["rightflowHnadleRef"].flowAsVal = "";
            this.$refs["rightflowHnadleRef"].flowAs = false;
          }
          this.$refs["leftflowHnadleRef"].outputSource = val;
          this.$refs["rightflowHnadleRef"].isUnidirectional =
            this.$refs["leftflowHnadleRef"].isUnidirectional;
          this.$refs["leftflowHnadleRef"].isUnidirectional = isUnidirectional;
        }
      });
    },
    setAnnotation(annotationListObjects) {
      this.$nextTick(() => {
        // 自定义注解整理
        this.$refs.notesRef.treeItems = reverseJson(
          annotationListObjects,
          "dist"
        );

        // treeData
        // const { name, elements } = annotationListObjects[0];
        const index = annotationListObjects.findIndex((i) => i.name == "dist");
        // dist数据整理回显
        if (index != -1) {
          this.$refs.notesRef.form = {
            parallel: annotationListObjects[index].elements.find(
              (item) => item.key == "parallel"
            ).value,
            execGroup: annotationListObjects[index].elements.find(
              (item) => item.key == "execGroup"
            ).value,
            checkedImplement: annotationListObjects[index].elements.find(
              (item) => item.key == "execGroup"
            ).value
              ? true
              : false,
            checkedParallel: annotationListObjects[index].elements.find(
              (item) => item.key == "parallel"
            ).value
              ? true
              : false,
          };
          this.$refs.notesRef.checked = true; //打开async输入框
        } else {
          this.$refs.notesRef.form = {
            parallel: "",
            execGroup: "",
            checkedParallel: false,
            checkedImplement: false,
          };
          this.$refs.notesRef.checked = false; //打开async输入框
        }
      });
    },
    inputExtensions(val) {
      this.grouping.groupBy = [
        this.extensionsLR &&
          this.extensionsLR.length !== 0 &&
          this.extensionsLR[0].name,
      ];
    },
    setAttrArr(attrArr) {
      attrArr.forEach((item) => {
        item.id = generateId();
        item.value = item.name;
        item.disabled = false;
      });
    },
    setqueryInput(queryInput, sourceCell) {
      if (queryInput) {
        const { joinType, left, right } = queryInput;
        this.setFlowData(queryInput, "left", "leftflowHnadleRef");
        this.setFlowData(queryInput, "right", "rightflowHnadleRef");
        let lrArr = [];
        if (right.as) {
          lrArr.push({
            id: "right",
            name: right.as,
            value: right.as,
            valueType: right.as,
          });
        }
        if (left.as) {
          lrArr.push({
            id: "left",
            name: left.as,
            value: left.as,
            valueType: left.as,
          });
        }
        const lrTarArr = setLrTarArr(sourceCell, {
          left: {
            as: left.as,
            isAttrLr: this.$refs["leftflowHnadleRef"].outputSource,
          },
          right: {
            as: right.as,
            isAttrLr: this.$refs["rightflowHnadleRef"].outputSource,
          },
        });
        lrArr = lrArr.concat(lrTarArr);
        this.$store.commit("projection/setAttrMetaData", {
          arr: lrArr,
          keyName: "funArrAll",
        });

        if (queryInput.on) {
          this.onVal = queryInput.on;
        } else {
          this.onVal = "";
        }

        if (joinType) {
          this.joinType = joinType;
        }
      } else {
        let lrArr = [];
        lrArr.push({
          id: "right",
          name: this.$refs["rightflowHnadleRef"].outputSource,
          value: this.$refs["rightflowHnadleRef"].outputSource,
          valueType: this.$refs["rightflowHnadleRef"].outputSource,
        });
        lrArr.push({
          id: "left",
          name: this.$refs["leftflowHnadleRef"].outputSource,
          value: this.$refs["leftflowHnadleRef"].outputSource,
          valueType: this.$refs["leftflowHnadleRef"].outputSource,
        });
        const lrTarArr = setLrTarArr(sourceCell, {
          left: {
            as: "",
            isAttrLr: this.$refs["leftflowHnadleRef"].outputSource,
          },
          right: {
            as: "",
            isAttrLr: this.$refs["rightflowHnadleRef"].outputSource,
          },
        });
        lrArr = lrArr.concat(lrTarArr);
        this.$store.commit("projection/setAttrMetaData", {
          arr: lrArr,
          keyName: "funArrAll",
        });
      }
    },
    changeRadio(row) {
      const { value, valueType } = row;
      this.onVal = valueType || value;
    },
    setFlowData(queryInput, key, refKey) {
      let {
        from,
        streamHandlerList,
        as: flowAs,
        isUnidirectional,
      } = queryInput[key];
      this.$refs[refKey].flowAsVal = flowAs || "";
      this.$refs[refKey].flowAs = flowAs ? true : false;
      this.$refs[refKey].isUnidirectional = isUnidirectional;
      this.$refs[refKey].outputSource = from || "";
      if (streamHandlerList && streamHandlerList.length !== 0) {
        streamHandlerList = setStreamHandlerList(
          streamHandlerList || [],
          this.extensions || []
        );
        if (this.$refs.leftflowHnadleRef) {
          this.$refs[refKey].streamHandlerList = streamHandlerList;
          this.$refs[refKey].streamHandlerChecked = true;
        }
      } else {
        this.$refs.leftflowHnadleRef.streamHandlerChecked = false;
      }
    },
    //删除orderBy
    handDelOrderBy(i) {
      this.output.orderBy.splice(i, 1);
    },
    // 添加
    handAddOrderBy() {
      this.output.orderBy.push({
        id: generateId(),
        attrValue: "",
        sortValue: "ASC",
        order: "ASC",
        attributeList: this.attributeList,
      });
    },
    handClose() {
      this.$emit("handClose");
    },
    isCheck() {
      // 在提交 的时候 判断是否选中清空数据
      // 是否有用户自定义属性
      if (this.grouping.select.type == "ALL") {
        // this.grouping.select.value = [];
        this.grouping.select.value = "*";
      }
      // 按属性分组
      if (!this.grouping.attrChecked) {
        this.grouping.groupBy = [];
      }
      // 按过滤分组
      if (!this.grouping.checkedFilter) {
        this.grouping.having = "";
      }
      // 按属性排序
      if (!this.output.orderCh) {
        this.output.orderBy = [];
      }
      // 限制
      if (!this.output.checkedLimit) {
        this.output.limit = 0;
      }
      // 位移
      if (!this.output.checkedOffset) {
        this.output.offset = 0;
      }
      // 输出速率
      if (!this.output.checkedOutputRateLimit) {
        this.output.outputRateLimit = "";
      }
      // set如果没选中 不传set
      if (!this.output.queryOutput.output.checkedSet) {
        this.output.queryOutput.output.set = undefined;
      }
    },
    submit() {
      // 流处理 queryInput
      // 注解
      const notesList = this.$refs.notesRef.getNotes();
      const treeItems = this.$refs.notesRef.treeItems;
      const queryInput = {
        joinType: this.joinType,
        type: "JOIN", //PROJECTION
        joinWith: "STREAM",
        left: {
          ...this.$refs.leftflowHnadleRef.getFlowData(),
        },
        right: {
          ...this.$refs.rightflowHnadleRef.getFlowData(),
        },
        on: this.onVal,
      };
      // 判断选择框是否选择-没有选择的清空数据
      this.isCheck();
      // 最终的提交数据
      const subData = {
        // 输出
        ...this.output,
        // 投影
        ...this.grouping,
        // 注解
        ...notesList,
        queryName: this.searchForm.queryName,
        queryInput,
        name: this.searchForm.queryName,
        treeItems: treeItems,
        relateData: this.nodeDataRight.relateData,
      };
      // 表单验证
      if (validate(subData)) {
        let returnData = {
          display: false,
          type: "queryLists",
          keyType: "JOIN",
          objectState: this.nodeDataRight.objectState,
          nodeData: subData,
          nodeDataRight: this.nodeDataRight,
        };
        // 存储到vuex-后续不需要可以删除
        this.$emit("returnSource", returnData);
      }
    },
    // async getMetadata() {
    //   const { data } = await getMetadata();
    //   // 数据整理(函数,过滤,窗口)
    //   let extensionsObj = setFunctiondata(data, this.nodeDataRight.relateData);
    //   //存入vuex
    //   this.$store.commit("projection/setMetadata", extensionsObj);
    // },
  },
};
</script>

<style lang='scss' scoped>
.source_box {
  margin-bottom: 16px;
  margin-top: 16px;
  .title {
    margin-bottom: 12px;
  }
}
.projection_box {
  display: flex;
  width: 100%;
  .content {
    padding-right: 10px;
    width: 100%;
    height: 80vh;
    overflow: scroll;
    overflow-x: hidden;
  }
}
</style>